﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ys_dec
{
    class Putbb
    {
        Byte[] seg = new byte[0x200];
        Byte[] cbuf = new byte[0x10000];
        int flag;
        int fc;
        int cpos,slen;
        public Putbb()
        {
            this.cpos=0;
            this.slen=0;
            this.flag=0;
            this.fc=8;
        }
        public void PutBits(int b, int c) //Put c bits
        {
            int bit;
            int mask = 1 << (c - 1);
            for (int i = 0; i < c; i++)
            {
                bit = (b & mask) >> (c - i - 1);
                mask >>= 1;

                flag |= (bit << fc);
                fc++;
                if (fc > 16)
                {
                    Console.WriteLine(String.Format("Out Flag 0x{0:X4}", flag));
                    cbuf[cpos++] = (byte)(flag & 0xFF);
                    flag >>= 8;
                    cbuf[cpos++] = (byte)(flag & 0xFF);
                    flag >>= 8;
                    fc -=16;
                    Array.Copy(seg, 0, cbuf, cpos, slen);
                    cpos += slen;
                    Console.Write("Put Bytes: ");
                    for (int ii = 0; ii < slen; ii++)
                        Console.Write(String.Format("0x{0:X2} ", seg[ii]));
                    Console.WriteLine();
                    slen = 0;
                }
            }
            Console.WriteLine(String.Format("Flag 0x{0:X4} {1}", flag, fc));
        }
        public void PutBit(int b)  // Put 1 bit
        {
            PutBits(b & 1, 1);
        }
        public void PutByte(byte b) //Put 1 byte
        {
            seg[slen++] = b;
        }
        public void PutBytes(byte[] bs, int len) //Put an array of bytes
        {
            Array.Copy(bs, 0, seg, slen, len);

        } 
        public byte[] GetCompressData()  // Return the compressed data
        {
            while (fc > 1 && slen > 0)
            {
                PutBit(0);
            }
            byte[] ret = new byte[cpos];
            Array.Copy(cbuf, ret, cpos);

            Console.Write("Seg out: ");
            foreach (byte b in ret)
                Console.Write(String.Format("0x{0:X2} ", b));
            Console.WriteLine();
            return ret;
        }

    }
}
